package com.gp.billsrecord.base

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
/*列表内容中一条一条数据控制的类的基类*/
abstract class BaseRecyclerViewAdapter<T : Any, VB : ViewBinding> :
    RecyclerView.Adapter<SimpleViewHolder<T, VB>>() {
    private val list: ArrayList<T> = initList()

    fun initList(): ArrayList<T> {
        return arrayListOf()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder<T, VB> {
        val binding = onCreateBinding(LayoutInflater.from(parent.context), parent, viewType)
        return SimpleViewHolder(::onBind, binding)
    }

    abstract fun onCreateBinding(inflater: LayoutInflater, parent: ViewGroup, viewType: Int): VB

    override fun onBindViewHolder(holder: SimpleViewHolder<T, VB>, position: Int) =
        holder.bind(list[position])

    override fun getItemCount(): Int = list.size

    abstract fun onBind(data: T, binding: VB)
    fun updateList(newList: List<T>) {
        list.clear()
        list.addAll(newList)
        notifyDataSetChanged()
    }
}

class SimpleViewHolder<T, VB : ViewBinding>(
    private val onBind: (T, VB) -> Unit,
    private val binding: VB
) :
    RecyclerView.ViewHolder(binding.root) {

    fun bind(t: T) {
        onBind(t, binding)
    }
}
